package com.hx.core.jsonTemplate;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.template.AbstractTemplate;

import java.io.*;
import java.util.Map;

/**
 * 自定义模板引擎——模板类
 */
public class CustomTemplate extends AbstractTemplate implements Serializable {
    private StringBuilder stringBuilder;
    private String prefix;
    private String suffix;

    public CustomTemplate(StringBuilder stringBuilder, String prefix, String suffix) {
        this.stringBuilder = stringBuilder;
        this.prefix = prefix;
        this.suffix = suffix;
    }

    @Override
    public void render(Map<?, ?> bindingMap, Writer writer) {
        for (Object key : bindingMap.keySet()) {
            String keyStr = StrUtil.concat(false, prefix, String.valueOf(key), suffix);
            String valStr = String.valueOf(bindingMap.get(key));
            int startIndex = stringBuilder.indexOf(keyStr);
            if (startIndex <= 0) continue;
            int endIndex = startIndex + keyStr.length();
            stringBuilder.replace(startIndex, endIndex, valStr);
        }
        try {
            writer.append(stringBuilder.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void render(Map<?, ?> bindingMap, OutputStream out) {
        // TODO
    }
}
